import React, { createElement } from "react";
import Nav from "@components/nav";
import { UserOutlined } from '@ant-design/icons';
import moment from 'moment';
import './topicInfo.less'
import { Avatar, Button, Col, Comment, Divider, Form, Input, List, Row, Tooltip } from 'antd';
import BasicLayout from "@/src/layouts";
import { LikeOutlined, LikeFilled } from '@ant-design/icons';
import userStore from "@common/userStore";
import TopicComment from "@components/comment";
import API from "@common/api.js";
import renderMarkdown from "../../components/markdownViewer/MarkdownViewer";
import JsxParser from "react-jsx-parser";
const { TextArea } = Input;

const Editor = ({ onChange, onSubmit, submitting, value }) => (
  <div>
    <Form.Item>
      <TextArea id="commentEditor" rows={4} onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item>
      <Button htmlType="submit" loading={submitting} onClick={onSubmit} type="primary">
        评论
      </Button>
    </Form.Item>
  </div>
);


class TopicInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '',
      description: '',
      username: '',
      likes: '',
      createDatetime: '',
      type: '',
      totalThumb: '',
      totalComment: '',
      comments: [],
      submitting: false,
      value: ''
      , content: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleSubmit() {
    if (!this.state.value) {
      return;
    }

    this.setState({
      submitting: true,
    });

    setTimeout(() => {
      var __create_datetime = moment();
      var _create_datetime = __create_datetime.format("YYYY-MM-DD HH:mm:ss");
      let data = {
        talkId: this.topicID,
        content: this.state.value,
        create_datetime: _create_datetime,
      }
      console.log(data);
      // 添加一条新的评论，并且返回该评论的id
      API.addComment(data).then(response => {
        let newCommentID = response.data
        console.log(newCommentID);
        // this.forceUpdate();
        // this.setState({
        //   __tmp: new Date()
        // });
        // let newCommentID = '12345'; //测试用
        // API.getAllComment(talkId)
        console.log(userStore.getState().username)
        this.setState({
          submitting: false,
          value: '',
          comments: [
            ...this.state.comments,
            {
              commentID: newCommentID,
              username: userStore.getState().username,
              avatar: userStore.getState().avatar,
              content: this.state.value,
              createDatetime: __create_datetime.fromNow()
            },
          ],
        });
      })

      //this.props.form.setFields({'commentEditor': ''})
    }, 1000);

  };

  handleChange(e) {
    this.setState({
      value: e.target.value,
    });
  };


  componentDidMount() {
    this.topicID = this.props.match.params.topicID;
    //console.log(this.props);
    //console.log(this.topicID);
    API.getTopicInfo(this.topicID).then(response => {
      response = response.data;
      console.log('这里是', response);
      this.setState({
        title: response.title,
        type: response.type,
        username: response.username,
        likes: response.likes,
        createDatetime: response.createDatetime,
        totalThumb: response.totalThumb,
        totalComment: response.totalComment,
      });
      console.log(this.state);
      renderMarkdown(response.content).then((replaced) => {
        this.setState({ content: <JsxParser jsx={replaced} /> });
      });
    });

    API.getAllComment(this.topicID).then(response => {
      response = response.data;
      console.log(response);
      this.setState({
        comments: response,
      })
      console.log(this.state)
    });


    /*this.state.comments是一个列表，每个元素是一个名为commentID键与其值的键值对，形如this.state.comments = [
      {
        commentID: '123',
      },
      {
        commentID: '3453',
      },
      {
        commentID: '6574',
      },
    ];*/
  }

  render() {
    return (
      <div id='topicInfoContainer'>
        <BasicLayout header={<Nav />}>
          <Row justify="left" align={"middle"} gutter={[208, { xs: 8, sm: 16, md: 24, lg: 32 }]}>
            <div id="topicInfoTitle">
              <Col span={36}>
                <span>{this.state.title}</span>
              </Col>
            </div>
          </Row>
          <Divider orientation="left"></Divider>
          <Row justify="left" align={"middle"} gutter={[208, { xs: 8, sm: 16, md: 24, lg: 32 }]}>
            <Col span={5} push={1}>
              <Avatar id="topicInfoAvatar" size={60} icon={<UserOutlined />} />

            </Col>
            <span id="topicInfoUserName">{this.state.username}</span>
            {/* <Divider id="topicInfoDivider">-</Divider> */}
            <Col span={23}>
              <div id="topicInfoText">
                {this.state.content}
                {/*{console.log(this.state.content)}*/}
              </div>
            </Col>
          </Row>
          <Divider style={{fontSize: 30}}>评论</Divider>
          
          <Row>
            {/*<div id="topicInfoComment">*/}

            <Col span={20} push={1}>
              <List
                className="comment-list"
                header={`${this.state.comments.length} replies`}
                itemLayout="horizontal"
                dataSource={this.state.comments}
                renderItem={item => (
                  <li>
                    <TopicComment
                      data={item}
                    />
                    <Divider orientation="left"></Divider>
                  </li>
                )}
              />
            </Col>
            {/*</div>*/}
          </Row>
          <Divider orientation="left"></Divider>
          <Row>
            <Col span={20} push={2}>
              <Editor
                onChange={this.handleChange}
                onSubmit={this.handleSubmit}
                submitting={this.submitting}
                value={this.value}
              />
            </Col>
          </Row>
        </BasicLayout>
      </div>
    )
  }
}

export default TopicInfo;